/*
   Detect if there is a noise
   Created by Randall Maas, Tuesday October 20 2009
   Copyright (c) 2009, Randall Maas
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

   Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

   Neither the name of Blackwood Designs, LLC nor the names of its contributors
   may be used to endorse or promote products derived from this software without
   specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
   THE POSSIBILITY OF SUCH DAMAGE.
*/

// A few portions here are lifted from
//http://blogs.msdn.com/coding4fun/archive/2009/10/08/9905168.aspx

using System;
using System . Threading;
using NAudio;
using NAudio.Wave;

partial class Program
{
   /// <summary>
   /// A flag used to indicate some sound was found
   /// </summary>
   static volatile int AudioTrigger=0;

   static double AudioThresh  = 0.8;
   static double AudioThresh2 = 0.09;

   /// <summary>
   /// Enable the audio subsystem to detect noise etc
   /// </summary>
   /// <returns></returns>
   static WaveIn[] StartMics()
   {
      int NumDevices = WaveIn.DeviceCount;
      WaveIn[] AudIns = new WaveIn[NumDevices ];
      for (int waveInDevice = 0; waveInDevice < NumDevices ; waveInDevice++)
      {
         AudIns[waveInDevice] = new WaveIn();
         AudIns[waveInDevice] . DeviceNumber = waveInDevice;
         AudIns[waveInDevice] . DataAvailable += waveIn_DataAvailable;
         AudIns[waveInDevice] . WaveFormat = new WaveFormat(8000, 1); // 8 Khz Mono (it's not important
         AudIns[waveInDevice] . StartRecording();
      }
      return AudIns;
   }

   /// <summary>
   /// Disable the stuff in the audio subsystem that we enabled
   /// </summary>
   /// <param name="AudIns"></param>
   static void StopMics(WaveIn[] AudIns)
   {
      if (null == AudIns)
        return;
      foreach(WaveIn W in AudIns)
      {
         W . StopRecording();
         W . Dispose();
      }
   }


   /// <summary>
   /// Receive the audio buffer and see if there is noise
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   static void waveIn_DataAvailable(object sender, WaveInEventArgs e)
   {
      bool   Tr    = false;
      double Sum2  = 0;
      int    Count = e.BytesRecorded / 2;
      for (int index = 0; index < e.BytesRecorded; index += 2)
      {
         double Tmp = (short)((e.Buffer[index + 1] << 8) | e.Buffer[index + 0]);
         Tmp /= 32768.0;
         Sum2 += Tmp*Tmp;
         if (Tmp > AudioThresh)
           Tr = true;
      }
      Sum2 /= Count;

      // If the Mean-Square is greater than a threshold, set a flag to indicate that noise has happened
      if (Tr || Sum2 > AudioThresh2)
        Interlocked . Exchange(ref AudioTrigger, 1);
   }

}
